<template>
  <div class="app-container">
    <div class="top-toolbar">
      <div class="search-box">
        <el-popover
          placement="bottom-start"
          :width="400"
          trigger="hover"
          popper-class="search-popover"
        >
          <template #reference>
            <el-button type="primary" class="light-button">
              <el-icon><Search /></el-icon>
              高级搜索
            </el-button>
          </template>
          <el-form :model="queryParams" ref="queryRef" :inline="true">
            <el-form-item label="开票日期" prop="dateRange">
              <el-date-picker
                v-model="queryParams.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="凭证号码" prop="invoiceNumber">
              <el-input
                v-model="queryParams.invoiceNumber"
                placeholder="请输入凭证号码"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="发票种类" prop="invoiceType">
              <el-select
                v-model="queryParams.invoiceType"
                placeholder="请选择发票种类"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="dict in fp_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-select
                v-model="queryParams.customerName"
                placeholder="请选择客户名称"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="dict in kh_name"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="发票状态" prop="voidOrNot">
              <el-select
                v-model="queryParams.voidOrNot"
                placeholder="请选择发票状态"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="dict in zuofei"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-popover>
      </div>
      <div class="right-buttons">
        <el-button
          type="primary"
          class="light-button"
          :disabled="single"
          @click="handleFetchInvoice"
          >取票</el-button
        >
        <el-button
          type="primary"
          class="light-button"
          @click="handleAdd"
          v-hasPermi="['invoice:invoice:add']"
          >新增</el-button
        >
        <el-button
          type="danger"
          class="light-button"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['invoice:invoice:remove']"
          >删除</el-button
        >
        <el-button type="primary" class="light-button">生成凭证</el-button>
        <el-dropdown>
          <el-button type="primary" class="light-button">
            更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="handleExport"
                v-hasPermi="['invoice:invoice:export']"
                >导出</el-dropdown-item
              >
              <el-dropdown-item>打印</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="invoiceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="50"
        fixed="left"
      />
      <el-table-column
        label="发票号码"
        align="center"
        prop="invoiceNumber"
        fixed="left"
      />
      <el-table-column
        label="开票日期"
        align="center"
        prop="invoiceDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.invoiceDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发票类型" align="center" prop="invoiceType">
        <template #default="scope">
          <dict-tag :options="fp_type" :value="scope.row.invoiceType" />
        </template>
      </el-table-column>
      <el-table-column label="发票代码" align="center" prop="invoiceCode" />
      <el-table-column label="客户名称" align="center" prop="customerName">
        <template #default="scope">
          <dict-tag :options="kh_name" :value="scope.row.customerName" />
        </template>
      </el-table-column>
      <el-table-column label="地址、电话" align="center" prop="address" />
      <el-table-column
        label="纳税人识别号"
        align="center"
        prop="taxpayerIdentification"
      />
      <el-table-column
        label="开户行及账号"
        align="center"
        prop="bankAndNumber"
      />
      <el-table-column label="金额" align="center" prop="amount">
        <template #default="scope">
          <span>{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="税率" align="center" prop="taxRate">
        <template #default="scope">
          <span>{{ scope.row.taxRate }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="税额" align="center" prop="taxAmount">
        <template #default="scope">
          <span>{{ scope.row.taxAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" prop="voidOrNot">
        <template #default="scope">
          <dict-tag :options="zuofei" :value="scope.row.voidOrNot" />
        </template>
      </el-table-column>
      <el-table-column label="模板名称" align="center" prop="templateName">
        <template #default="scope">
          <dict-tag :options="mo" :value="scope.row.templateName" />
        </template>
      </el-table-column>
      <el-table-column label="是否生成单据" align="center" prop="receipt">
        <template #default="scope">
          <dict-tag :options="dan" :value="scope.row.receipt" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['invoice:invoice:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['invoice:invoice:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销项发票对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="invoiceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发票号码" prop="invoiceNumber">
          <el-input v-model="form.invoiceNumber" placeholder="请输入发票号码" />
        </el-form-item>
        <el-form-item label="开票日期" prop="invoiceDate">
          <el-date-picker
            clearable
            v-model="form.invoiceDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开票日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发票类型" prop="invoiceType">
          <el-select v-model="form.invoiceType" placeholder="请选择发票类型">
            <el-option
              v-for="dict in fp_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票代码" prop="invoiceCode">
          <el-input v-model="form.invoiceCode" placeholder="请输入发票代码" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-select v-model="form.customerName" placeholder="请选择客户名称">
            <el-option
              v-for="dict in kh_name"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址、电话" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址、电话" />
        </el-form-item>
        <el-form-item label="开具方式" prop="issuingMethod">
          <el-checkbox-group v-model="form.issuingMethod">
            <el-checkbox
              v-for="dict in kai"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="项目" prop="item">
          <el-select v-model="form.item" placeholder="请选择项目">
            <el-option
              v-for="dict in xiangmu"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="纳税人识别号" prop="taxpayerIdentification">
          <el-input
            v-model="form.taxpayerIdentification"
            placeholder="请输入纳税人识别号"
          />
        </el-form-item>
        <el-form-item label="开户行及账号" prop="bankAndNumber">
          <el-input
            v-model="form.bankAndNumber"
            placeholder="请输入开户行及账号"
          />
        </el-form-item>
        <el-form-item label="是否作废" prop="voidOrNot">
          <el-radio-group v-model="form.voidOrNot">
            <el-radio
              v-for="dict in zuofei"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="上传附件" prop="uploadAttachment">
          <file-upload v-model="form.uploadAttachment" />
        </el-form-item>
        <el-form-item label="发票数据" prop="fpId">
          <el-input v-model="form.fpId" placeholder="请输入发票数据" />
        </el-form-item>
        <el-form-item label="凭证ID" prop="pzId">
          <el-input v-model="form.pzId" placeholder="请输入凭证ID" />
        </el-form-item>
        <el-form-item label="业务类型 *" prop="businessTypel">
          <el-select v-model="form.businessTypel" placeholder="请选择业务类型">
            <el-option
              v-for="dict in yewu"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName">
          <el-select v-model="form.templateName" placeholder="请选择模板名称">
            <el-option
              v-for="dict in mo"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否生成单据" prop="receipt">
          <el-select v-model="form.receipt" placeholder="请选择是否生成单据">
            <el-option
              v-for="dict in dan"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">发票数据信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTaxItem"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteTaxItem"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="taxItemList"
          :row-class-name="rowTaxItemIndex"
          @selection-change="handleTaxItemSelectionChange"
          ref="taxItem"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column
            label="规格型号"
            prop="specificationModel"
            width="150"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.specificationModel"
                placeholder="请输入规格型号"
              />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.quantity"
                placeholder="请输入数量"
                @input="handleCalculate(scope.row)"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="uninPrice" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.uninPrice"
                placeholder="请输入单价"
                @input="handleAmountChange1(scope.row)"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.amount"
                placeholder="金额"
                :readonly="true"
              />
            </template>
          </el-table-column>
          <el-table-column label="税率" prop="taxRate" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.taxRate"
                placeholder="请输入税率"
                @input="handleTaxRateChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="税额" prop="taxAmount" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.taxAmount"
                placeholder="请输入税额"
              />
            </template>
          </el-table-column>
          <el-table-column label="计税项目" prop="taxationItem" width="150">
            <template #default="scope">
              <el-select
                v-model="scope.row.taxationItem"
                placeholder="请选择计税项目"
              >
                <el-option
                  v-for="dict in taxationItems"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="计税方法"
            prop="taxCalculationMethod"
            width="150"
          >
            <template #default="scope">
              <el-select
                v-model="scope.row.taxCalculationMethod"
                placeholder="请选择计税方法"
              >
                <el-option
                  v-for="dict in taxCalculationMethods"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      <!-- 底部合计金额 -->

      <div style="margin-top: 10px; text-align: right; padding-right: 20px">
        <span style="margin-right: 20px"
          >不含税金额：{{ totalTaxNotIncluded }}</span
        >
        <span style="margin-right: 20px">税额：{{ totalTax }}</span>
        <span>价税合计：{{ totalWithTax }}</span>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Invoice">
import {
  listInvoice,
  getInvoice,
  delInvoice,
  addInvoice,
  updateInvoice,
  exportInvoice,
} from "@/api/invoice/invoice";
import { Search } from "@element-plus/icons-vue";
import { ref, reactive, toRefs, watch, computed } from "vue";

const { proxy } = getCurrentInstance();
const { xiangmu, zuofei, yewu, fp_type, dan, kh_name, kai, mo } = proxy.useDict(
  "xiangmu",
  "zuofei",
  "yewu",
  "fp_type",
  "dan",
  "kh_name",
  "kai",
  "mo"
);
const totalTaxNotIncluded = computed(() => {
  return taxItemList.value
    .reduce((total, item) => {
      const amount = parseFloat(item.amount) || 0;
      return total + amount;
    }, 0)
    .toFixed(2);
});
const totalTax = computed(() => {
  return taxItemList.value
    .reduce((total, item) => {
      const amount = parseFloat(item.amount) || 0;
      const taxRate = parseFloat(item.taxRate) || 0;
      return total + (amount * taxRate) / 100;
    }, 0)
    .toFixed(2);
});

const totalWithTax = computed(() => {
  const notIncluded = parseFloat(totalTaxNotIncluded.value) || 0;
  const tax = parseFloat(totalTax.value) || 0;
  return (notIncluded + tax).toFixed(2);
});

const taxationItems = [
  { value: "1", label: "采购支出" },
  { value: "2", label: "办公货物" },
  { value: "3", label: "运费支出" },
  { value: "4", label: "出差支出" },
  { value: "5", label: "其他" },
];

const taxCalculationMethods = [
  { value: "1", label: "凭证模板一" },
  { value: "2", label: "凭证模板二" },
  { value: "3", label: "凭证模板三" },
  { value: "4", label: "凭证模板四" },
  { value: "5", label: "其他" },
];

const invoiceList = ref([]);
const taxItemList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTaxItem = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    dateRange: [new Date("2025-03-01"), new Date("2025-03-31")],
    invoiceDateRange: [],
    voucherDateRange: [],
    voucherType: "",
    voucherNo: "",
    invoiceType: "",
    invoiceNumber: "",
    customerName: "",
    invoiceStatus: "",
    voucherStatus: "",
    documentStatus: "",
  },
  rules: {
    // 添加子表验证规则
    taxItemList: [
      {
        type: "array",
        required: true,
        message: "请至少添加一条发票数据",
        trigger: "change",
      },
    ],
    invoiceType: [
      { required: true, message: "发票类型不能为空", trigger: "change" },
    ],
    invoiceNumber: [
      { required: true, message: "发票号码不能为空", trigger: "blur" },
    ],
    customerName: [
      { required: true, message: "客户名称不能为空", trigger: "change" },
    ],
    invoiceDate: [
      { required: true, message: "开票日期不能为空", trigger: "change" },
    ],
    businessTypel: [
      { required: true, message: "业务类型不能为空", trigger: "change" },
    ],
    amount: [{ required: true, message: "金额不能为空", trigger: "blur" }],
    taxRate: [{ required: true, message: "税率不能为空", trigger: "blur" }],
    taxAmount: [{ required: true, message: "税额不能为空", trigger: "blur" }],
    taxationItem: [
      { required: true, message: "征税项目不能为空", trigger: "change" },
    ],
    taxCalculationMethod: [
      { required: true, message: "计税方法不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
/** 查询销项发票列表 */
function getList() {
  loading.value = true;
  listInvoice(queryParams.value).then((response) => {
    invoiceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    invoiceNumber: null,
    invoiceDate: null,
    invoiceType: null,
    invoiceCode: null,
    customerName: null,
    address: null,
    issuingMethod: [],
    item: null,
    taxpayerIdentification: null,
    bankAndNumber: null,
    voidOrNot: null,
    remark: null,
    uploadAttachment: null,
    fpId: null,
    pzId: null,
    businessTypel: null,
    templateName: null,
  };
  taxItemList.value = [];
  proxy.resetForm("invoiceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  // 处理日期范围
  const params = {
    ...queryParams.value,
    beginInvoiceDate: queryParams.value.invoiceDateRange
      ? queryParams.value.invoiceDateRange[0]
      : undefined,
    endInvoiceDate: queryParams.value.invoiceDateRange
      ? queryParams.value.invoiceDateRange[1]
      : undefined,
    beginVoucherDate: queryParams.value.voucherDateRange
      ? queryParams.value.voucherDateRange[0]
      : undefined,
    endVoucherDate: queryParams.value.voucherDateRange
      ? queryParams.value.voucherDateRange[1]
      : undefined,
  };

  // 删除不需要传递的参数
  delete params.invoiceDateRange;
  delete params.voucherDateRange;

  queryParams.value.pageNum = 1;
  loading.value = true;

  listInvoice(params)
    .then((response) => {
      invoiceList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    ...queryParams.value,
    dateRange: [new Date("2025-03-01"), new Date("2025-03-31")],
    invoiceDateRange: [],
    voucherDateRange: [],
    voucherType: "",
    voucherNo: "",
    invoiceType: "",
    invoiceNumber: "",
    customerName: "",
    invoiceStatus: "",
    voucherStatus: "",
    documentStatus: "",
  };
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加销项发票";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getInvoice(_id).then((response) => {
    form.value = response.data;
    form.value.issuingMethod = form.value.issuingMethod.split(",");
    taxItemList.value = response.data.taxItemList;
    open.value = true;
    title.value = "修改销项发票";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["invoiceRef"].validate((valid) => {
    if (valid) {
      form.value.issuingMethod = form.value.issuingMethod.join(",");
      form.value.taxItemList = taxItemList.value;
      if (form.value.id != null) {
        updateInvoice(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInvoice(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除销项发票编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delInvoice(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 发票数据序号 */
function rowTaxItemIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 发票数据添加按钮操作 */
function handleAddTaxItem() {
  let obj = {};
  obj.specificationModel = "";
  obj.unit = "";
  obj.quantity = "";
  obj.uninPrice = "";
  obj.amount = "";
  obj.taxRate = "";
  obj.taxAmount = "";
  obj.taxationItem = "";
  obj.taxCalculationMethod = "";
  obj.taxNotIncluded = "";
  obj.totalValueTax = "";
  taxItemList.value.push(obj);
}

/** 发票数据删除按钮操作 */
function handleDeleteTaxItem() {
  if (checkedTaxItem.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的发票数据数据");
  } else {
    const taxItems = taxItemList.value;
    const checkedTaxItems = checkedTaxItem.value;
    taxItemList.value = taxItems.filter(function (item) {
      return checkedTaxItems.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleTaxItemSelectionChange(selection) {
  checkedTaxItem.value = selection.map((item) => item.index);
}

// 计算合计金额、税额和价税合计
const calculateTotals = () => {
  let totalAmount = 0;
  let totalTax = 0;
  let totalWithTax = 0;

  taxItemList.value.forEach((item) => {
    const amount = parseFloat(item.amount) || 0;
    const taxRate = parseFloat(item.taxRate) || 0;

    totalAmount += amount;
    const tax = amount * (taxRate / 100);
    totalTax += tax;
  });

  totalWithTax = totalAmount + totalTax;

  form.value.totalAmount = totalAmount.toFixed(2);
  form.value.totalTax = totalTax.toFixed(2);
  form.value.totalWithTax = totalWithTax.toFixed(2);
};

// 处理金额变化
const handleAmountChange1 = (row) => {
  const quantity = parseFloat(row.quantity) || 0;
  const uninPrice = parseFloat(row.uninPrice) || 0;
  row.amount = (quantity * uninPrice).toFixed(2);
  calculateTotals();
};

// 处理税率变化
const handleTaxRateChange = (row) => {
  const amount = parseFloat(row.amount) || 0;
  const taxRate = parseFloat(row.taxRate) || 0;
  row.taxAmount = (amount * (taxRate / 100)).toFixed(2);
  calculateTotals();
};

// 监听taxItemList的变化
watch(
  taxItemList,
  () => {
    calculateTotals();
  },
  { deep: true }
);

/** 导出按钮操作 */
function handleExport() {
  proxy.$modal.confirm("是否确认导出所有销项发票数据项?").then(() => {
    proxy.$modal.loading("正在导出数据，请稍候...");
    
    // 处理导出参数，与查询参数保持一致
    const params = {
      ...queryParams.value,
      beginInvoiceDate: queryParams.value.dateRange ? queryParams.value.dateRange[0] : undefined,
      endInvoiceDate: queryParams.value.dateRange ? queryParams.value.dateRange[1] : undefined,
      invoiceType: queryParams.value.invoiceType,
      invoiceNumber: queryParams.value.invoiceNumber,
      customerName: queryParams.value.customerName,
      voidOrNot: queryParams.value.voidOrNot
    };

    // 删除不需要的参数
    delete params.dateRange;
    delete params.pageNum;
    delete params.pageSize;

    // 发起导出请求
    exportInvoice(params)
     .then((response) => {
        // 处理后端返回的二进制数据
        const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `销项发票数据_${Date.now()}.xlsx`;
        a.click();
        window.URL.revokeObjectURL(url);

        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("导出成功");
      })
     .catch((error) => {
        console.error('导出失败:', error);
        proxy.$modal.closeLoading();
        proxy.$modal.msgError("导出失败：" + (error.msg || error.message || '未知错误'));
      });
  });
}

// 添加取票处理函数
/** 取票按钮操作 */
function handleFetchInvoice() {
  if (!ids.value || ids.value.length === 0) {
    proxy.$modal.msgError("请选择要取票的发票");
    return;
  }

  // 获取选中的发票ID
  const invoiceId = ids.value[0];

  // 跳转到发票模板页面并传递ID
  proxy.$router.push({
    path: "/invoice/template",
    query: { id: invoiceId },
  });
}

getList();
</script>
